<template>
  <div ref="chart" :style="{ height: height, width: width }" style="padding: 0 20px"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DeviceStatusDistribution',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '60px'
    },
    chartData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chartInstance: null,
      chart: null
    };
  },
  watch: {
    chartData: {
      handler() {
        this.initChart();
      },
      deep: true
    }
  },
  mounted() {
    this.chart = this.$refs.chart;
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    renderItem(params, api) {
      const categoryIndex = api.value(0);
      const start = api.coord([api.value(1), categoryIndex]);
      const end = api.coord([api.value(2), categoryIndex]);
      const height = api.size([0, 1])[1] * 0.2;
      const rectShape = echarts.graphic.clipRectByRect(
        {
          x: start[0],
          y: start[1] - height / 2,
          width: end[0] - start[0],
          height: height
        },
        {
          x: params.coordSys.x,
          y: params.coordSys.y,
          width: params.coordSys.width,
          height: params.coordSys.height
        }
      );
      return (
        rectShape && {
          type: 'rect',
          shape: rectShape,
          style: api.style()
        }
      );
    },
    initChart() {
      if (!this.chartData.length || !this.chart) return;

      const data = [];
      const startTime = new Date(this.chartData[0].startTime).getTime();
      const endTime = new Date(this.chartData[this.chartData.length - 1].endTime).getTime();
      const types = [
        { name: '运行', color: '#75d874', status: 1 },
        { name: '待机', color: '#e0bc78', status: 2 },
        { name: '报警', color: '#bd6d6c', status: 5 },
        { name: '关机', color: 'Gray', status: 4 },
        { name: '断线', color: 'DarkGray', status: -99 }
      ];

      this.chartData.forEach((val) => {
        let baseTime = new Date(val['startTime']).getTime();
        let duration = Number(val.duration);
        let yieldValue = val.yield || 0;
        data.push({
          name: types.find((item) => item.status == val.state)?.name || '未知',
          value: [0, baseTime, (baseTime += duration), duration, yieldValue],
          itemStyle: {
            normal: {
              color: types.find((item) => item.status == val.state)?.color || '#cccccc'
            }
          }
        });
      });

      const series = types.map((val) => ({
        name: val.name,
        type: 'custom',
        renderItem: this.renderItem,
        itemStyle: {
          opacity: 0.8,
          color: val.color
        },
        encode: {
          x: [1, 2],
          y: 0
        },
        data: data
      }));

      const option = {
        tooltip: {
          formatter: (params) => {
            if (!params || !params.value) return '';
            const startTime = new Date(params.value[1]).toLocaleString();
            const endTime = new Date(params.value[2]).toLocaleString();
            return `${params.marker}${params.name}<br/>开始时间: ${startTime}<br/>结束时间: ${endTime}`;
          }
        },
        dataZoom: [
          {
            type: 'slider',
            show: false,
            filterMode: 'weakFilter',
            showDataShadow: false,
            top: 0,
            height: 10,
            borderColor: 'transparent',
            backgroundColor: '#e2e2e2',
            handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z',
            handleSize: 20,
            handleStyle: {
              shadowBlur: 6,
              shadowOffsetX: 1,
              shadowOffsetY: 2,
              shadowColor: '#aaa'
            },
            labelFormatter: '',
            start: 0,
            end: 70
          },
          {
            type: 'inside',
            filterMode: 'weakFilter'
          }
        ],
        grid: {
          top: -15,
          left: 15,
          right: 15,
          bottom: 0
        },
        xAxis: {
          min: startTime,
          max: endTime,
          scale: true,
          axisLabel: {
            show: true,
            margin: -20,
            formatter: (value) => new Date(value).toLocaleTimeString()
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        yAxis: {
          data: [],
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          }
        },
        series
      };

      if (!this.chartInstance) {
        this.chartInstance = echarts.init(this.chart);
      }
      this.chartInstance.setOption(option);
    }
  }
};
</script>